package run.iget.admin.system.event;

import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import run.iget.admin.system.constant.AdminSystemConst;
import run.iget.admin.system.convert.AdminLogConvertConvert;
import run.iget.admin.system.entity.AdminLoginLog;
import run.iget.admin.system.service.AdminLoginLogService;
import run.iget.framework.common.util.ExceptionThrowUtils;
import run.iget.security.bean.SafeAuthUser;
import run.iget.security.event.AuthEventEnums;
import run.iget.security.event.SafeAuthEvent;

import java.util.Objects;

@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = AdminSystemConst.MODULE_NAME, name = "handleAdminLoginLog", havingValue = "true")
public class AdminLoginLogListener implements ApplicationListener<SafeAuthEvent> {

    private final AdminLoginLogService adminLoginLogService;

    @Async
    @Override
    public void onApplicationEvent(SafeAuthEvent event) {
        if (Objects.isNull(event) || Objects.isNull(event.getSource())) {
            return;
        }
        SafeAuthUser authUser = (SafeAuthUser) event.getSource();
        AuthEventEnums authEventEnum = event.getAuthEventEnum();
        AdminLoginLog adminLoginLog = AdminLogConvertConvert.I.to(authUser);
        switch (authEventEnum) {
            case LOGIN:
                adminLoginLogService.save(adminLoginLog);
                break;
            case LOGOUT:
                ExceptionThrowUtils.ofNull(adminLoginLog.getAdministratorId(), "用户标识不可为空");
                adminLoginLogService.remove(QueryWrapper.create(adminLoginLog));
                break;
        }
    }
}
